<?php
namespace app\lib;

use think\Db;

class WxUser {
    private $ty_id = 0;
    private $iv_id = '';
    private $iv_key = 'id';
    public $upInfo = null;
    public $userInfo = null;
    public $openid = '';
    public $err_msg; //系统return false后从此处获取错误消息

    //构造方法，初始化必要数据
    public function __construct($ty_id=0) {
        $this->ty_id = $ty_id;
    }
    /*
     * 初始化邀请
     * $iv_id 会员ID或者邀请码
     * $iv_mold id，iv
     * */
    public function initIv($iv_id='',$iv_mold='id'){
        switch ( $iv_mold ) {
            default:
                $this->iv_id = 0 < $iv_id?$iv_id:'';
                $this->iv_key = 'id'; //通过ID邀请
        }
    }
    public function getUserInfo($openid){
        $this->userInfo = Db::name('user')->field('id,nickname,headimgurl,realname,mobile,openid,unionid,token,ty_id')->where("openid='".$openid."'")->find();
    }
    /*
     * 设置用户信息
     * $data 用户信息
     * */
    public function setUserInfo($data=[]) {
        if( !isset($data['openid']) ) {
            $this->err_msg = '缺少openid';
            return false;
        }
        $this->openid = $data['openid'];
        $this->getUserInfo($this->openid);
        if( $this->userInfo ){
            if( $this->userInfo['headimgurl'] == '' ){
                Db::name('user')->where(['openid'=>$this->openid])->update(['nickname'=>$data['nickname'], 'headimgurl'=>$data['headimgurl']]);
            }
            $this->userInfo = array_merge($this->userInfo,$data);
            return true;
        }else{
            return $this->add($data);
        }
    }

    /*
     * $data为微信获取的用户数据*/
    public function add($data){
        $data['ty_id'] = $this->ty_id;
        $data['token'] = $this->getToken();
        Db::startTrans();
        try {
            $user_id = Db::name('user')->insertGetId($data);
            Db::name('user_ext')->insert(['id'=>$user_id,'ty_id'=>$this->ty_id,'create_time'=>time()]);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err_msg = $e->getMessage();
            return false;
        }
        $this->userInfo = ['id'=>$user_id,'up_id'=>0,'nickname'=>$data['nickname'],'headimgurl'=>$data['headimgurl'],'realname'=>'','mobile'=>'','token'=>$data['token'],'openid'=>$data['openid'],'ty_id'=>0];
        return true;
    }



    private function getToken(){
        return substr(md5(microtime(true)), 0, 6);
    }
}